<template>
  <div class="news-container">
    <el-card class="news-card">
      <template #header>
        <div class="card-header">
          <span>新闻公告管理</span>
          <el-button
type="primary" @click="handleAdd">
新增新闻公告
</el-button>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :model="searchForm"
label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keywords"
placeholder="请输入标题关键词" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类">
              <el-select v-model="searchForm.cate_id"
placeholder="请选择分类" clearable>
                <el-option label="全部"
value="" />
                <!-- 这里应该从后端获取分类列表 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button
type="primary" @click="handleSearch">
搜索
</el-button>
              <el-button @click="handleReset">
重置
</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 新闻公告列表 -->
      <el-table :data="newsList"
border v-loading="loading" stripe>
        <el-table-column prop="id"
label="ID" width="80" />
        <el-table-column prop="title"
label="标题" show-overflow-tooltip />
        <el-table-column prop="cate_name"
label="分类" width="120" />
        <el-table-column prop="admin_name"
label="发布人" width="120" />
        <el-table-column prop="view_count"
label="浏览量" width="100" />
        <el-table-column prop="create_time"
label="发布时间" width="160" />
        <el-table-column label="操作"
width="200" fixed="right">
          <template #default="scope">
            <el-button
type="primary" size="small" @click="handleView(scope.row)">
查看
</el-button>
            <el-dropdown @command="handleCommand">
              <el-button size="small">
                更多
                <i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', row: scope.row }">
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', row: scope.row }">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 查看新闻公告详情对话框 -->
    <el-dialog v-model="viewDialogVisible"
title="新闻公告详情" width="60%" destroy-on-close>
      <div v-if="currentNews">
        <el-descriptions :column="2"
border>
          <el-descriptions-item label="标题">
            {{ currentNews.title }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            {{ currentNews.cate_name }}
          </el-descriptions-item>
          <el-descriptions-item label="发布人">
            {{ currentNews.admin_name }}
          </el-descriptions-item>
          <el-descriptions-item label="发布时间">
            {{ currentNews.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="浏览量">
            {{ currentNews.view_count }}
          </el-descriptions-item>
        </el-descriptions>

        <el-card class="content-card">
          <template #header>
            <span>内容</span>
          </template>
          <div v-html="currentNews.content" />
        </el-card>

        <el-card
          v-if="currentNews.file_array && currentNews.file_array.length > 0"
          class="file-card"
        >
          <template #header>
            <span>附件</span>
          </template>
          <div class="file-list">
            <el-link
              v-for="file in currentNews.file_array"
              :key="file.id"
              :href="file.url"
              target="_blank"
              :underline="false"
            >
              <el-icon><Document /></el-icon>
              {{ file.name }}
            </el-link>
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="viewDialogVisible = false">
关闭
</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑新闻公告对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editingNewsId ? '编辑新闻公告' : '新增新闻公告'"
      width="60%"
      destroy-on-close
    >
      <el-form :model="newsForm"
:rules="newsRules" ref="newsFormRef" label-width="80px">
        <el-form-item label="标题"
prop="title">
          <el-input v-model="newsForm.title"
placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="分类"
prop="cate_id">
          <el-select v-model="newsForm.cate_id"
placeholder="请选择分类">
            <!-- 这里应该从后端获取分类列表 -->
          </el-select>
        </el-form-item>

        <el-form-item label="内容"
prop="content">
          <el-input v-model="newsForm.content"
type="textarea" :rows="6" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="附件">
          <!-- 附件上传组件待实现 -->
          <el-upload
            action="/upload"
            multiple
            :file-list="newsForm.fileList"
            :on-success="handleFileSuccess"
            :on-remove="handleFileRemove"
          >
            <el-button
size="small" type="primary">
点击上传
</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="状态"
prop="status">
          <el-radio-group v-model="newsForm.status">
            <el-radio :label="1">
发布
</el-radio>
            <el-radio :label="0">
草稿
</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">
取消
</el-button>
        <el-button
type="primary" @click="submitNews">
确定
</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown, Document } from '@element-plus/icons-vue'
  import axios from '@/utils/request'

  // 搜索表单
  const searchForm = ref({
    keywords: '',
    cate_id: '',
  })

  // 新闻公告列表数据
  const newsList = ref([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 查看对话框
  const viewDialogVisible = ref(false)
  const currentNews = ref(null)

  // 编辑对话框
  const editDialogVisible = ref(false)
  const editingNewsId = ref(0)
  const newsForm = ref({
    title: '',
    content: '',
    cate_id: '',
    file_ids: '',
    fileList: [],
    status: 1,
  })

  // 表单验证规则
  const newsRules = {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    cate_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
  }

  // 表单引用
  const newsFormRef = ref(null)

  // 获取新闻公告列表
  const getNewsList = async () => {
    loading.value = true
    try {
      const params = {
        page: currentPage.value,
        limit: pageSize.value,
        keywords: searchForm.value.keywords,
        cate_id: searchForm.value.cate_id,
      }

      const res = await axios.get('/oa/news/list', { params })
      if (res.data.code === 0) {
        newsList.value = res.data.data
        total.value = res.data.count
      } else {
        ElMessage.error(res.data.msg || '获取新闻公告列表失败')
      }
    } catch (error) {
      ElMessage.error('获取新闻公告列表失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    currentPage.value = 1
    getNewsList()
  }

  // 重置搜索条件
  const handleReset = () => {
    searchForm.value = {
      keywords: '',
      cate_id: '',
    }
    currentPage.value = 1
    getNewsList()
  }

  // 分页相关
  const handleSizeChange = val => {
    pageSize.value = val
    currentPage.value = 1
    getNewsList()
  }

  const handleCurrentChange = val => {
    currentPage.value = val
    getNewsList()
  }

  // 查看新闻公告详情
  const handleView = async row => {
    try {
      const res = await axios.get('/oa/news/view', {
        params: { id: row.id },
      })
      if (res.data.code === 0) {
        currentNews.value = res.data.data
        viewDialogVisible.value = true
      } else {
        ElMessage.error(res.data.msg || '获取新闻公告详情失败')
      }
    } catch (error) {
      ElMessage.error('获取新闻公告详情失败: ' + error.message)
    }
  }

  // 新增新闻公告
  const handleAdd = () => {
    editingNewsId.value = 0
    newsForm.value = {
      title: '',
      content: '',
      cate_id: '',
      file_ids: '',
      fileList: [],
      status: 1,
    }
    editDialogVisible.value = true
  }

  // 编辑新闻公告
  const handleEdit = async row => {
    // 这里应该从后端获取完整的新闻公告信息进行编辑
    ElMessage.info('编辑新闻公告功能待完善')
  }

  // 删除新闻公告
  const handleDelete = row => {
    ElMessageBox.confirm('确定要删除该新闻公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ElMessage.info('删除新闻公告功能待实现')
      })
      .catch(() => {
        // 取消删除
      })
  }

  // 处理下拉菜单命令
  const handleCommand = command => {
    const { action, row } = command
    switch (action) {
      case 'edit':
        handleEdit(row)
        break
      case 'delete':
        handleDelete(row)
        break
    }
  }

  // 附件上传成功处理
  const handleFileSuccess = (response, file, fileList) => {
    newsForm.value.fileList = fileList
    // 需要处理文件ID的收集
  }

  // 附件移除处理
  const handleFileRemove = (file, fileList) => {
    newsForm.value.fileList = fileList
    // 需要处理文件ID的移除
  }

  // 提交新闻公告
  const submitNews = () => {
    newsFormRef.value.validate(async valid => {
      if (valid) {
        try {
          const params = {
            ...newsForm.value,
          }

          let res
          if (editingNewsId.value) {
            // 编辑
            params.id = editingNewsId.value
            res = await axios.put('/oa/news/edit', params)
          } else {
            // 新增
            res = await axios.post('/oa/news/add', params)
          }

          if (res.data.code === 0) {
            ElMessage.success(editingNewsId.value ? '编辑成功' : '新增成功')
            editDialogVisible.value = false
            getNewsList()
          } else {
            ElMessage.error(res.data.msg || (editingNewsId.value ? '编辑失败' : '新增失败'))
          }
        } catch (error) {
          ElMessage.error((editingNewsId.value ? '编辑失败' : '新增失败') + ': ' + error.message)
        }
      }
    })
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getNewsList()
  })
</script>

<style scoped>
  .news-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .content-card,
  .file-card {
    margin-top: 20px;
  }

  .file-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .file-list .el-link {
    display: flex;
    align-items: center;
    gap: 5px;
  }
</style>
